package com.yiyuplatform.service.schedule.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.kevinsawicki.http.HttpRequest;
import com.yiyuplatform.config.WxConfig;
import com.yiyuplatform.service.schedule.ScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Map;

/**
 * \* Date: 2021/11/17
 * \* Time: 20:58
 * \* Description: 定时任务实现类
 * \
 */
@Slf4j
@Service
@Component
@EnableScheduling
@EnableAsync
public class ScheduleServiceImpl implements ScheduleService {
    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.appSecret}")
    private String appSecret;
    @Value("${wx.grantType}")
    private String grantType;
    @Value("${wxToken.url}")
    private String tokenUrl;
    /**
     * @Description: 定时获取全局唯一accessToken,调用微信后台API时需携带此access_token，服务器运行前调用一次
     * @Param:
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     */
    @Async
    @Scheduled(cron = "*/7200 * * * * ?")
    public void getUserAccessToken() {
        log.info("获取access_token");
        Map<String, Object> json = null;
        try {
            String accessTokenUrl=tokenUrl+"?"+"grant_type="+grantType+"&appid="+appId+"&secret="+appSecret;
            // 发送请求
            String response = HttpRequest.get(accessTokenUrl).body();
            System.out.println(response);
            ObjectMapper mapper = new ObjectMapper();
            json = mapper.readValue(response, Map.class);
            WxConfig.access_token=json.get("access_token").toString();
            log.info("获取access_token成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
